﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using HMIS.MVC.ViewModel;
using HMIS.MVC.CommonSupport;
using HMIS.FrameWork;
using HMIS.Infrastructure.Core.Authority;
using HMIS.Infrastructure.Facade.Authority;
using HMIS.FrameWork.Cache;
using System.ComponentModel;
using Iesi.Collections.Generic;

namespace HMIS.MVC.Controllers
{
	public class InfraHospUserController : BaseController
	{
		private readonly IHospUserFacade HospUserFacade;
		private readonly IDepartmentFacade DepartmentFacade;
		private readonly IRoleFacade RoleFacade;
		private readonly IMenuFacade MenuFacade;

		public InfraHospUserController(IHospUserFacade HospUserFacade, IDepartmentFacade DepartmentFacade, IRoleFacade RoleFacade, IMenuFacade MenuFacade)
		{
			this.HospUserFacade = HospUserFacade;
			this.DepartmentFacade = DepartmentFacade;
			this.RoleFacade = RoleFacade;
			this.MenuFacade = MenuFacade;
		}
		[Description("访问用户管理页面")]
		[ViewPage]
		public ActionResult HospUser()
		{
			return View();
		}

		[Description("获取用户列表")]
		public ActionResult GetPlist()
		{
			long total;
			var data = HospUserFacade.GetPlist(
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			return this.JsonFormat(
				new ExtGirdData<HospUser> { total = total, data = data },
				new string[] { "Department" });
		}

		[ExtResult]
		[Description("判断用户的名称、编码是否在类别下唯一")]
		public ActionResult IsFieldExist()
		{
			var result = HospUserFacade.IsFieldExist(Request["FieldName"], Request[Request["FieldName"]], Request["Id"]);
			return this.JsonFormat(new ExtResult { success = !result, msg = "已存在相同的项!" });

		}

		[ExtResult]
		[Description("添加、修改用户")]
		public ActionResult SaveOrUpdate()
		{
			HospUser entity;
			if (String.IsNullOrEmpty(Request["Id"]))
			{
				entity = new HospUser
				{
					Name = Request["Name"],
					LoginName = Request["LoginName"],
					Code = Request["Code"],
					Mobitl = Request["Mobitl"],
					Hometl = Request["Hometl"],
					Offitl = Request["Offitl"],
					Shortl = Request["Shortl"],
					DepartmentId = Request["DepartmentId"],
					UserGroup = Request["UserGroup"],
					PostId = Request["PostId"],
					Description = Request["Description"],
					InputCode1 = Request["InputCode1"],
					InputCode2 = Request["InputCode2"],
					InputCode3 = Request["InputCode3"],
					Pwd = HMIS.Infrastructure.Core.Authority.HospUser.GetPwdMD5(Request["Pwd"]),
					State = (PersonState)int.Parse(Request["State"]),

					//Departments = new HashedSet<Department>(),
					//Roles = new HashedSet<Role>(),
				};
				/*
				string[] depts = Request["Departments"].Split(',');
				for (int i = 0; i < depts.Length; i++)
				{
					entity.Departments.Add(DepartmentFacade.Load(depts[i]));
				}
				if (!String.IsNullOrEmpty(Request["Roles"]))
				{
					string[] roles = Request["Roles"].Split(',');
					for (int i = 0; i < depts.Length; i++)
					{
						entity.Roles.Add(RoleFacade.Load(roles[i]));
					}
				}
				*/
			}
			else
			{
				entity = HospUserFacade.GetById(Request["Id"]);
				entity.Mobitl = Request["Mobitl"];
				entity.Hometl = Request["Hometl"];
				entity.Offitl = Request["Offitl"];
				entity.Shortl = Request["Shortl"];
				entity.DepartmentId = Request["DepartmentId"];
				entity.PostId = Request["PostId"];
				entity.UserGroup = Request["UserGroup"];
				entity.InputCode1 = Request["InputCode1"];
				entity.InputCode2 = Request["InputCode2"];
				entity.InputCode3 = Request["InputCode3"];
				entity.Description = Request["Description"];
				entity.State = (PersonState)int.Parse(Request["State"]);
				/*
				entity.Departments.Clear();
				entity.Roles.Clear();
				string[] depts = Request["Departments"].Split(',');
				for (int i = 0; i < depts.Length; i++)
				{
					entity.Departments.Add(DepartmentFacade.Load(depts[i]));
				}
				if (!String.IsNullOrEmpty(Request["Roles"]))
				{
					string[] roles = Request["Roles"].Split(',');
					for (int i = 0; i < roles.Length; i++)
					{
						entity.Roles.Add(RoleFacade.Load(roles[i]));
					}
				}
				*/
			}

			HospUserFacade.SaveOrUpdate(entity);
			return this.JsonFormat(new ExtResult { success = true, id = entity.Id });
		}

		[ExtResult]
		[Description("删除用户基础资料项")]
		public ActionResult Delete()
		{
			HospUserFacade.Delete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[Description("获取用户实体")]
		public ActionResult GetHospUserById()
		{
			var entity = HospUserFacade.GetById(Request["Id"]);
			return this.JsonFormat(
				new ExtFormLoadData<HospUser> { data = new HospUser[] { entity } }, new string[] { "Departments", "Roles" }
				);
		}

		[Description("获取当前登录的用户信息")]
		public ActionResult GetCurrentUser()
		{
			var currentUser = new CurrentUser();
			return this.JsonFormat(
				new ExtGirdData<Person> { total = 1, data = new Person[] { currentUser.UserInfo } });
		}

		public ActionResult GetCurrentUserMenuPermission()
		{
			var currentUserMenu = new CurrentUser().AllMenuPermission;
			return this.JsonFormat(
				new ExtGirdData<MenuNode> { total = currentUserMenu.Count, data = currentUserMenu });
		}

		[Description("按机构和角色获取用户列表")]
		public ActionResult GetUserListByDep()
		{
			long total;
			var data = HospUserFacade.GetUserListByDep(
				Request["query"],
				Request["depcode"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			return this.JsonFormat(
				new ExtGirdData<object[]> { total = total, data = data },
				//new ExtGirdData<UserDepRole> { total = total, data = data },
				new string[] { "CustomType" });
		}

		//返回用户状态
		[Description("返回用户状态")]
		public ActionResult GetState()
		{
			var result = EnumDescription.ToList<PersonState>();
			return this.JsonFormat(result);
		}

		[Description("获得机构查询列表")]
		public ActionResult GetDeptList()
		{
			long total;
			var data = DepartmentFacade.QueryPlist(
				Request["query"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				out total);
			return this.JsonFormat(
				new ExtGirdData<Department> { data = data, total = total });
		}

		[Description("获得角色查询列表")]
		public ActionResult GetRoleQueryList()
		{
			long total;
			var data = RoleFacade.QueryPlist(
				Request["query"],
				int.Parse(Request["start"]),
				int.Parse(Request["limit"]),
				out total);
			return this.JsonFormat(
				new ExtGirdData<Role> { total = total, data = data });

		}

		[ExtResult]
		[Description("保存用户菜单项")]
		public ActionResult SaveUserMenu()
		{
			HospUser HospUser = HospUserFacade.GetByIdWithMenu(Request["Id"]);
			HospUser.MenuNodes.Clear();
			string[] MIds = Request["MId"].Split(',');
			for (int i = 0; i < MIds.Length; i++)
			{
				if (!string.IsNullOrEmpty(MIds[i]))
				{
					MenuNode MenuNode = MenuFacade.Load(MIds[i]);
					HospUser.MenuNodes.Add(MenuNode);
				}
			}
			HospUserFacade.SaveOrUpdate(HospUser);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("删除用户关联菜单对照项")]
		public ActionResult DeleteUserMenu()
		{
			HospUser HospUser = HospUserFacade.GetByIdWithMenu(Request["Id"]);
			string[] MIds = Request["MId"].Split(',');
			for (int i = 0; i < MIds.Length; i++)
			{
				if (!string.IsNullOrEmpty(MIds[i]))
				{
					MenuNode MenuNode = MenuFacade.Load(MIds[i]);
					HospUser.MenuNodes.Remove(MenuNode);
					HospUserFacade.SaveOrUpdate(HospUser);
				}
			}
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[Description("修改密码")]
		public ActionResult ChangePwd()
		{
			if (!System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
				throw new DemoHisException("用户未登录");//必须要用户Form验证后才能使用CurrentUser

			string loginName = System.Web.HttpContext.Current.User.Identity.Name;
			var authorityFacade = ContainerFactory.GetContainer().Resolve<IAuthorityFacade>();
			HospUser hpuser = authorityFacade.GetHospUserByName(loginName);
			authorityFacade.ChangeUserPwd(hpuser.Id, Request["OldPwd"], Request["NewPwd"]);

			return this.JsonFormat((new ExtResult { success = true }));
		}

		[Description("发送飞信邀请信息")]
		public ActionResult SendFetionAddSms()
		{
			string[] Ids = Request["Ids"].Split(',');
			for (int i = 0; i < Ids.Length; i++)
			{
				if (!string.IsNullOrEmpty(Ids[i]))
				{
					HospUser user = HospUserFacade.Get(Ids[i]);
					if (string.IsNullOrEmpty(user.Mobitl))
						throw new ValidationException("用户[" + user.Name + "]的手机号码为空!");
					HMIS.FrameWork.Common.SendSms.SendAddFetionByGetRequest(user.Mobitl);
				}
			}
			return this.JsonFormat((new ExtResult { success = true }));
		}
	}
}
